﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Transactions;
using System.Web.Mvc;
using ZBJF.Warranty.BLL;
using ZBJF.Warranty.Common.Common;
using ZBJF.Warranty.Common.Enums.System;
using ZBJF.Warranty.Model;
using ZBJF.Warranty.Model.ViewModel.Product;
using ZBJF.Warranty.WebProvider;

namespace ZBJF.Warranty.AdminSite.Controllers
{
    public class AccessoriesLevelController : BaseController
    {
        #region 配件等级页面 + ActionResult AccessoriesLevelIndex()
        public ActionResult AccessoriesLevelIndex()
        {
            return View();
        }
        #endregion

        #region 配件等级管理页面获取列表数据 + ActionResult AccessoriesLevelList(AccessoriesLevelModel model)
        /// <summary>
        /// 配件等级管理页面获取列表数据
        /// </summary>
        /// <returns></returns>
        public ActionResult AccessoriesLevelList(AccessoriesLevelModel model)
        {
            var total = 0;
            var list = (from a in ServiceFactory.AccessoriesLevelServiceInstance.GetPagingList(model, out total).AsNoTracking()
                        join b in ServiceFactory.ProductTypeServiceInstance.LoadEntities(t => true) on a.ProductTypeID equals b.ID into temp1
                        from c in temp1.DefaultIfEmpty()
                        join d in ServiceFactory.AccessoriesTypeServiceInstance.LoadEntities(t => true) on a.AccessoriesTypeID equals d.ID into temp2
                        from e in temp2.DefaultIfEmpty()
                        select new
                        {
                            a.ID,
                            a.AccessoriesLevelName,
                            a.AccessoriesLevelCode,
                            a.IsAvailable,
                            a.LastModifyBy,
                            a.LastModifyTime,
                            c.ProductName,
                            e.AccessoriesName
                        }).ToList();
            return Json(new
            {
                sEcho = model.sEcho,
                iTotalRecords = total,
                iTotalDisplayRecords = total,
                aaData = list
            }, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 配件等级编辑 + ActionResult AccessoriesLevelEdit(int id)
        /// <summary>
        /// 配件等级编辑
        /// </summary>
        /// <returns></returns>
        public ActionResult AccessoriesLevelEdit(int id)
        {
            ViewBag.ShowTitle = id > 0 ? "编辑配件等级" : "添加配件等级";
            var AccessoriesLevel = ServiceFactory.AccessoriesLevelServiceInstance.LoadByID(id);
            return View(AccessoriesLevel);
        }

        #endregion

        #region 保存配件等级 + ActionResult SaveAccessoriesLevel(AccessoriesLevel model)

        [HttpPost]
        [ValidateInput(false)]
        //保存配件等级
        public ActionResult SaveAccessoriesLevel(AccessoriesLevel model)
        {
            var responseResult = new ResponseResult
            {
                OpreateType = model.ID > 0 ? OpreateType.Update : OpreateType.Add
            };

            var serv = ServiceFactory.AccessoriesLevelServiceInstance;
            model.AccessoriesLevelName = model.AccessoriesLevelName.Trim();
            if (model.ID == 0)
            {
                if (serv.IsExist(model.ProductTypeID, model.AccessoriesTypeID, model.AccessoriesLevelName))
                {
                    responseResult.Message = "该配件等级已经存在";
                    TempData["ResponseResult"] = responseResult;
                    return RedirectToAction("AccessoriesLevelEdit", new { id = model.ID });
                }
                model.CreateTime = DateTime.Now;
                model.CreateBy = CurrentUser.UserAccount;
                model.LastModifyBy = CurrentUser.UserAccount;
                model.LastModifyTime = DateTime.Now;

                using (TransactionScope ts = new TransactionScope())
                {
                    var entity = serv.AddEntities(model);
                    responseResult.Success = entity.ID > 0;
                    if (!responseResult.Success)
                    {
                        ts.Dispose();
                        TempData["ResponseResult"] = responseResult;
                        return RedirectToAction("AccessoriesLevelEdit", new { id = model.ID });
                    }

                    entity.AccessoriesLevelCode = CommonMethod.GenerateCode("PJDJ", entity.ID.ToString());
                    if (!serv.UpdateEntities(entity))
                    {
                        ts.Dispose();
                        responseResult.Message = "操作失败！设置配件等级编码失败";
                        TempData["ResponseResult"] = responseResult;
                        return RedirectToAction("AccessoriesLevelEdit", new { id = model.ID });
                    }
                    ts.Complete();
                }
            }
            else
            {
                var entity = serv.LoadByID(model.ID);
                if (entity != null)
                {
                    if (serv.IsExist(model.ProductTypeID, model.AccessoriesTypeID, model.AccessoriesLevelName, model.ID))
                    {
                        responseResult.Message = "已存在同名的配件等级，请修改配件等级名称";
                        TempData["ResponseResult"] = responseResult;
                        return RedirectToAction("AccessoriesLevelEdit", new { id = model.ID });
                    }
                    //entity = ReflectHelper<AccessoriesLevel, AccessoriesLevel>.CloneT1ToT2(model, entity);
                    entity.ProductTypeID = model.ProductTypeID;
                    entity.AccessoriesTypeID = model.AccessoriesTypeID;
                    entity.AccessoriesLevelName = model.AccessoriesLevelName;
                    entity.Remark = model.Remark;
                    entity.IsAvailable = model.IsAvailable;
                    entity.LastModifyBy = CurrentUser.UserAccount;
                    entity.LastModifyTime = DateTime.Now;
                    responseResult.Success = ServiceFactory.AccessoriesLevelServiceInstance.UpdateEntities(entity);
                }
                else
                {
                    responseResult.Message = "该配件等级不存在或已被删除";
                }
            }
            TempData["ResponseResult"] = responseResult;
            return responseResult.Success ? RedirectToAction("AccessoriesLevelIndex") : RedirectToAction("AccessoriesLevelEdit", new { id = model.ID });
        }


        #endregion

        #region 禁用/启用配件等级 + JsonResult UpdateStatus(int id, bool isAvailable)
        /// <summary>
        /// 禁用/启用配件等级
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <param name="isAvailable">启用/禁用</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult UpdateStatus(int id, bool isAvailable)
        {
            var entity = ServiceFactory.AccessoriesLevelServiceInstance.LoadByID(id);
            var success = false;
            if (entity != null)
            {
                entity.IsAvailable = isAvailable;
                entity.LastModifyBy = CurrentUser.UserAccount;
                entity.LastModifyTime = DateTime.Now;
                success = ServiceFactory.AccessoriesLevelServiceInstance.UpdateEntities(entity);
            }
            return Json(new
            {
                success = success,
                message = success ? "修改成功" : "修改失败"
            });
        }
        #endregion


        #region 获取配件等级 + JsonResult GetAccessoriesLevel(string AccessoriesTypeIds,string Ids)
        public JsonResult GetAccessoriesLevel(string AccessoriesTypeIds, string Ids)
        {
            //配件类型
            List<int> accessoriesTypeIds = new List<int>();
            if (!string.IsNullOrEmpty(AccessoriesTypeIds))
                accessoriesTypeIds = AccessoriesTypeIds.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(Int32.Parse).ToList();


            //需要排除掉的配件等级
            List<int> ids = new List<int>();
            if (!string.IsNullOrEmpty(Ids))
                ids = Ids.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(Int32.Parse).ToList();

            var entities = (from a in ServiceFactory.AccessoriesLevelServiceInstance
                                .LoadEntities(o => o.IsAvailable == true && accessoriesTypeIds.Contains(o.AccessoriesTypeID) && !ids.Contains(o.ID)).AsNoTracking()
                            join b in ServiceFactory.AccessoriesTypeServiceInstance.LoadEntities(t => true).AsNoTracking() on a.AccessoriesTypeID equals b.ID
                            join c in ServiceFactory.ProductTypeServiceInstance.LoadEntities(t => true).AsNoTracking() on b.ProductTypeID equals c.ID
                            select new
                            {
                                a.AccessoriesLevelName,
                                a.ID,
                                b.AccessoriesName,
                                c.ProductName,
                                AccessoriesTypeId = b.ID,
                                ProductTypeId= c.ID
                            }).ToList();

            return Json(new { Result = true, Data = entities }, JsonRequestBehavior.AllowGet);
        }
        #endregion
    }
}